import config from "@/config";
import storage from "@/utils/storage";
import constant from "@/utils/constant";
import { isHttp, isEmpty } from "@/utils/validate";
import { login, logout, getInfo } from "@/api/login";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { getUserConfig } from "@/api/system/userConfig";
import { getUserConfigWithCache, extractWorkInfo } from "@/utils/userConfig";

import defAva from "@/static/images/profile.jpg";

const baseUrl = config.baseUrl;

const user = {
  namespaced: true,
  state: {
    token: getToken(),
    id: storage.get(constant.id),
    nickname: storage.get(constant.nickname),
    username: storage.get(constant.name),
    mobile: storage.get(constant.mobile),
    email: storage.get(constant.email),
    deptName: storage.get(constant.deptName),
    avatar: storage.get(constant.avatar),
    roles: storage.get(constant.roles),
    permissions: storage.get(constant.permissions),
    menus: storage.get(constant.menus) || [],
    userConfig: storage.get(constant.userConfig) || {}, // 用户配置数据
    workInfo: storage.get(constant.workInfo) || {}, // 工作信息
    shiftInfo: {
      shiftName: "早班",
      teamName: "A班组",
    },
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_ID: (state, id) => {
      state.id = id;
      storage.set(constant.id, id);
    },
    SET_NICKNAME: (state, nickname) => {
      state.nickname = nickname;
      storage.set(constant.nickname, nickname);
    },
    SET_USERNAME: (state, username) => {
      state.username = username;
      storage.set(constant.username, username);
    },
    SET_MOBILE: (state, mobile) => {
      state.mobile = mobile;
      storage.set(constant.mobile, mobile);
    },
    SET_EMAIL: (state, email) => {
      state.email = email;
      storage.set(constant.email, email);
    },
    SET_DEPT_NAME: (state, deptName) => {
      state.deptName = deptName;
      storage.set(constant.deptName, deptName);
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar || defAva; // 添加默认头像保护
      storage.set(constant.avatar, avatar);
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
      storage.set(constant.roles, roles);
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
      storage.set(constant.permissions, permissions);
    },
    SET_MENUS: (state, menus) => {
      state.menus = menus;
      storage.set(constant.menus, menus);
    },
    SET_SHIFT_INFO: (state, shiftInfo) => {
      state.shiftInfo = shiftInfo;
    },
    SET_USER_CONFIG: (state, userConfig) => {
      state.userConfig = userConfig;
      storage.set(constant.userConfig, userConfig);
    },
    SET_WORK_INFO: (state, workInfo) => {
      state.workInfo = workInfo;
      storage.set(constant.workInfo, workInfo);
    },
  },

  getters: {
    userInfo: (state) => {
      return {
        id: state.id,
        nickname: state.nickname,
        username: state.username,
        mobile: state.mobile,
        email: state.email,
        deptName: state.deptName,
        avatar: state.avatar,
        roles: state.roles,
        permissions: state.permissions,
        phonenumber: state.phonenumber,
        sex: state.sex,
        dept: state.dept,
        posts: state.posts,
        createTime: state.createTime,
        loginDate: state.loginDate,
        loginIp: state.loginIp,
      };
    },
    workInformation: (state) => {
      return state.workInfo;
    },
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim();
      const password = userInfo.password;
      const captchaVerification = userInfo.captchaVerification;
      return new Promise((resolve, reject) => {
        login(username, password, captchaVerification)
          .then((res) => {
            res = res.data;
            console.log(res, "res");
            // 设置 token
            setToken(res);
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 获取用户信息（包含用户配置）
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then(async (res) => {
            res = res.data; // 读取 data 数据
            console.log("getInfo response data:", res);
            const user = res.user;
            const avatar =
              user == null || user.avatar === "" || user.avatar == null
                ? require("@/static/images/profile.jpg")
                : user.avatar;
            const nickname =
              user == null || user.nickname === "" || user.nickname == null
                ? ""
                : user.nickname;
            const username =
              user == null || user.username === "" || user.username == null
                ? ""
                : user.username;
            const mobile =
              user?.mobile || user?.phonenumber || user?.phone || "";
            const email = user?.email || "";
            const deptName =
              user?.dept?.deptName || user?.deptName || user?.dept?.name || "";

            // 获取用户ID并存储
            const userId = user?.userId || user?.id || user?.userid;
            if (userId) {
              commit("SET_ID", userId);
            }

            // 处理权限和菜单数据，兼容不同结构
            const permissions = res.permissions || res || [];
            const roles = res.roles || [];
            const menus = res.menus || [];

            commit("SET_ROLES", roles.length > 0 ? roles : []);
            commit(
              "SET_PERMISSIONS",
              permissions.length > 0 ? permissions : []
            );
            commit("SET_MENUS", menus.length > 0 ? menus : []);
            commit("SET_NICKNAME", nickname);
            commit("SET_USERNAME", username);
            commit("SET_MOBILE", mobile);
            commit("SET_EMAIL", email);
            commit("SET_DEPT_NAME", deptName);
            commit("SET_AVATAR", avatar);

            // 获取用户配置信息
            try {
              // 尝试不同的ID字段名称
              const userId = user?.userId || user?.id || user?.userid;

              if (userId) {
                // 强制刷新，确保每次登录都获取最新的配置信息
                const userConfig = await getUserConfigWithCache(userId, true);
                if (userConfig) {
                  commit("SET_USER_CONFIG", userConfig);
                  const workInfo = extractWorkInfo(userConfig);
                  commit("SET_WORK_INFO", workInfo);
                }
              }
            } catch (error) {
              console.error("获取用户配置失败:", error);
              // 如果是未登录错误，不显示错误提示，静默处理
              if (error.message !== "用户未登录") {
                console.warn("用户配置获取失败，但继续执行其他逻辑");
              }
              // 不抛出错误，继续执行其他逻辑
            }

            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 退出系统
    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(() => {
            commit("SET_ROLES", []);
            commit("SET_PERMISSIONS", []);
            removeToken();
            storage.clean();
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },

    // 更新用户信息（仅更新本地状态，不调用API）
    UpdateUserInfo({ commit }, userInfo) {
      return new Promise((resolve) => {
        // 直接更新本地Vuex状态，不调用API
        if (userInfo.nickname) {
          commit("SET_NICKNAME", userInfo.nickname);
        }
        if (userInfo.phonenumber) {
          // 可以添加手机号验证逻辑
        }
        if (userInfo.email) {
          // 可以添加邮箱验证逻辑
        }
        if (userInfo.avatar) {
          commit("SET_AVATAR", userInfo.avatar);
        }
        if (userInfo.mobile) {
          commit("SET_MOBILE", userInfo.mobile);
        }
        if (userInfo.email) {
          commit("SET_EMAIL", userInfo.email);
        }
        if (userInfo.deptName) {
          commit("SET_DEPT_NAME", userInfo.deptName);
        }

        resolve({ success: true, message: "用户信息更新成功" });
      });
    },

    // 获取用户配置（带缓存）
    getUserConfigWithCache(
      { commit, state },
      { userId, forceRefresh = false }
    ) {
      return new Promise(async (resolve, reject) => {
        try {
          const userConfig = await getUserConfigWithCache(userId, forceRefresh);
          if (userConfig) {
            commit("SET_USER_CONFIG", userConfig);
            const workInfo = extractWorkInfo(userConfig);
            commit("SET_WORK_INFO", workInfo);
          }
          resolve(userConfig);
        } catch (error) {
          console.error("获取用户配置失败:", error);
          // 如果是未登录错误，返回空配置而不是拒绝
          if (error.message === "用户未登录") {
            console.warn("用户未登录，返回空配置");
            resolve({});
          } else {
            reject(error);
          }
        }
      });
    },
  },
};

export default user;
